//
//  JXComtDetailCtl.m
//  JiaoX
//
//  Created by yinqy on 15/3/6.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXComtDetailCtl.h"
#import "JXReplyCommentView.h"
#import "MJRefresh.h"
#import "ComtDetailHeaderView.h"
#import "ForumDataTool.h"
#import "ChildComtCell.h"
#import "ChildComtFrame.h"
#import "CommentUtils.h"
#import "JXPostsDetailCtl.h"



//去请求商品主评论详情的地址
#define PROD_COMTDETAIL @"product/commentDetail"
//去请求测主主评论详情的地址
#define REVIEWS_COMTDETAIL @"reviews/commentDetail"
//去请求帖子主评论详情的地址
#define POSTS_COMTDETAIL @"forum/commentDetail"


@interface JXComtDetailCtl ()<JXReplyCommentViewDelegate,UITableViewDataSource,UITableViewDelegate,ComtDetailHeaderViewDelegate>
{
    //回复需要用到的东西
    NSString *_userIdOther;
    NSString *_userNameOther;
    NSString *_commentType;//回复的类型：0代表回复的是帖子，1代表回复的是主评论，2代表回复的是子评论

}


@property (nonatomic, copy) NSString *commentId;
@property (nonatomic, copy) NSString *replyUrl;
@property (nonatomic, copy) NSString *replyType;
@property (nonatomic, copy) NSString *replyId;//商品id或者 评测id 或者帖子id
@property (nonatomic, copy) NSString *comtDetailUrl;


@property (nonatomic, assign) int hintType;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)JXReplyCommentView *replyView;
@property (nonatomic, copy) NSString *placeHolderStr;
@property (nonatomic, strong)ComtDetailHeaderView *headerView;
@property (nonatomic, strong)NSMutableArray *childComtArray;
@property (nonatomic, strong)CommentInfo *mainComtInfo;
@end

@implementation JXComtDetailCtl


-(instancetype)initWithComtId:(NSString *)comtId ReplyType:(NSString *)replyType replyId:(NSString *)replyId startFrom:(NSInteger)startFrom mainComtInfo:(CommentInfo *)mainComtInfo{
    self = [super init];
    if (self) {
        if (mainComtInfo!=nil) {
            mainComtInfo.reComment = nil;
            mainComtInfo.isShowAll = 1;
        }
        self.mainComtInfo = mainComtInfo;
        
        self.commentId = comtId;
        self.replyType = replyType;
        self.replyId = replyId;
        self.title = @"评论";
        
        if ([replyType isEqualToString:REPLY_TYPE_PRODID]) {
            self.placeHolderStr = @"闲话这货";
            self.comtDetailUrl = PROD_COMTDETAIL;
            self.replyUrl = @"product/recomment";
        }else if([replyType isEqualToString:REPLY_TYPE_REVIEWSID]){
            self.placeHolderStr = @"闲话这货";
            self.comtDetailUrl = REVIEWS_COMTDETAIL;
            self.replyUrl = @"reviews/recomment";
        }else{
            self.placeHolderStr = @"聊聊嘛";
            self.comtDetailUrl = POSTS_COMTDETAIL;
            self.replyUrl = @"forum/recomment";
        }
        
        if (startFrom == 0) {
            self.title = @"回复我的";
            self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"nav_ic_lookposts" highImageName:@"nav_ic_lookposts_heighlight" target:self action:@selector(lookPost)];
        }
        self.childComtArray = [NSMutableArray array];
    }
    return self;
}

-(void)lookPost{
    JXPostsDetailCtl *ctl = [[JXPostsDetailCtl alloc]initWithPostId:self.replyId];
    [self.navigationController pushViewController:ctl animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:JXGlobalColorBg];
    
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    [_tableView setHeight:_tableView.height-49];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setTableFooterView:[[UIView alloc]init]];
    [self.view addSubview:_tableView];
    
    _replyView = [[JXReplyCommentView alloc]initWithPlaceholder:self.placeHolderStr];
    _replyView.x = 0;
    _replyView.y = self.view.height-49;
    _replyView.delegate = self;
    [self.view addSubview:_replyView];
    
    if (self.mainComtInfo) {
        [self setHeaderViewForTableView:self.mainComtInfo];
    }
    
    [_tableView addHeaderWithTarget:self action:@selector(headerRefresh)];
    [_tableView addFooterWithTarget:self action:@selector(footerRefresh)];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView headerBeginRefreshing];

}

-(void)setHeaderViewForTableView:(CommentInfo *)comtInfo{
    self.headerView = [[ComtDetailHeaderView alloc]init];
    [self.headerView setDelegate:self];
    CommentViewFrame *frame = [[CommentViewFrame alloc]init];
    frame.comtInfo = comtInfo;
    [self.headerView setComtframe:frame];
    [self.tableView setTableHeaderView:self.headerView];
}

-(void)requestMainComtData:(NSString *)lastComtId{
    [ForumDataTool getComtDetailListWithComtId:self.commentId lastComtId:lastComtId url:self.comtDetailUrl success:^(CommentInfo *result) {
        [Utils refreshComplete:self.tableView];
        if ([Utils isBlankString:result.data]) {
            if ([Utils isBlankString:lastComtId]) {//如果lastComID为空，则清空集合里面的内容
                [self.childComtArray removeAllObjects];
            }
            [self convertComtToComtframe:result];
            result.reComment = nil;
            result.isShowAll = 1;
            if ([Utils isBlankString:lastComtId] && self.mainComtInfo == nil) {
                [self setHeaderViewForTableView:result];
            }
            [self.tableView reloadData];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"加载失败"];
    }];
}

-(void)convertComtToComtframe:(CommentInfo *)comtinfo{
    for (CommentInfo *childInfo in comtinfo.reComment) {
        ChildComtFrame *frame = [[ChildComtFrame alloc]initWithWidth:ITEM_WIDTH];
        [frame setChildComtInfo:childInfo];
        [self.childComtArray addObject:frame];
    }
}

-(void)headerRefresh{
    [self requestMainComtData:@""];
}

-(void)footerRefresh{
    ChildComtFrame *frame = [self.childComtArray lastObject];
    [self requestMainComtData:frame.childComtInfo.commentId];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.childComtArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChildComtFrame *frame = self.childComtArray[indexPath.row];
    ChildComtCell *cell = [ChildComtCell cellWithTableView:tableView];
    [cell.itemView setComt:frame.childComtInfo];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChildComtFrame *frame = self.childComtArray[indexPath.row];
    return frame.frame.size.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ChildComtFrame *frame = self.childComtArray[indexPath.row];
    _commentType = @"1";
    _userIdOther = frame.childComtInfo.commentUserId;
    _userNameOther = frame.childComtInfo.commentName;
    [_replyView setPlaceHolder:[NSString stringWithFormat:@"回复@%@",_userNameOther]];
    [_replyView becomeFirstResponder];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 顶部view　delegate
-(void)headerViewReplyBtnClick:(UIButton *)btn{
    //回复主评论
    _commentType = @"1";
    [_replyView becomeFirstResponder];
}

#pragma Mark - 论坛评论相关 delegte

-(void)bottomViewReplyBtnClick:(NSString *)replyContent{
    MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
    [CommentUtils replyCommentWithController:self replyUrl:self.replyUrl ReplyType:self.replyType replyMainId:self.replyId commentId:_commentId replyContent:replyContent userIdOther:_userIdOther commentType:_commentType success:^(CommentInfo *result) {
        //这儿做了两件事，把键盘关掉，隐藏hud
        [self.view endEditing:YES];
        if ([Utils isBlankString:result.data]) {
            //在这儿处理回复成功相关逻辑
            [self replyResultHandle:self.commentId currentComtId:result.commentId userIdOther:_userIdOther userNameOther:_userNameOther replyContent:replyContent];
            //处理完逻辑之后重置相关参数，重置完毕之后再将hud关掉，并弹出回复成功tip
            [self reSetReplyParams];[DialogUtils showTipsWithView:self.navigationController.view String:@"回复成功"];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
        [HUD hide:YES];
        
    } failure:^(NSError *error) {
        [HUD hide:YES];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"回复失败"];
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self reSetReplyParams];
    [self.view endEditing:YES];
}

- (void)reSetReplyParams{
    _commentType = @"1";
    _userIdOther = nil;
    _userNameOther = nil;
    [_replyView setPlaceHolder:nil];
    [_replyView setText:nil];
}


/**
 * 回复成功之后相关处理
 *
 * @param commentId     被回复的主评论id
 * @param currentComtId 当前即将添加到评论里面去的id。是服务器返回的
 * @param userIdOther   被回复人的id
 * @param userNameOther 被回复人的名字
 * @param replyContent  回复的内容
 */
-(void)replyResultHandle:(NSString *)commentId currentComtId:(NSString *)currentComtId userIdOther:(NSString *)userIdOther userNameOther:(NSString *)userNameOther replyContent:(NSString *)replyContent{
    
    NSString *headImage = [UserDefaultsHelper stringForKey:KEY_USER_IMG];
    NSString *commentUserId = [UserDefaultsHelper stringForKey:KEY_USER_ID];
    NSString *commentName = [UserDefaultsHelper stringForKey:KEY_NICK_NAME];
    
    CommentInfo *info = [[CommentInfo alloc]init];
    [info setHeadImage:headImage];
    [info setCommentUserId:commentUserId];
    [info setCommentId:[NSString stringWithFormat:@"%@",currentComtId]];
    [info setCommentName:commentName];
    [info setCommentContent:replyContent];
    [info setCommentTime:@"刚刚"];
    [info setUserIdOther:userIdOther];
    [info setUserNameOther:userNameOther];
    [info setIsShowAll:1];
    [info setCommentGender:[UserDefaultsHelper stringForKey:KEY_USER_GENDER]];
    [info setCommentLevel:(int)[UserDefaultsHelper integerForKey:KEY_USER_LEVEL]];
    
    
    //回复主评论 或者 //回复子评论
    
    ChildComtFrame *frame = [[ChildComtFrame alloc]initWithWidth:ITEM_WIDTH];
    [frame setChildComtInfo:info];
    
    
    if ([self.replyType isEqualToString:REPLY_TYPE_POSTSID]) {//如果是帖子。子评论添加到后面。
        [self.childComtArray addObject:frame];
    }else{
        [self.childComtArray insertObject:frame atIndex:0];
    }

    [self.tableView reloadData];
    [self reSetReplyParams];
}




@end
